const fs = require('fs');
const multiparty = require('multiparty');
const Config = require('../config/index');
const Joi = require("joi");
const path = require('path');
const GROUP_NAME = 'upload';

/*
 * Check File existence and create if not exist
 */

let checkFileExist = function() {
    fs.exists(Config.publicFolder, function(exists) {
        if (exists === false) fs.mkdirSync(Config.publicFolder);

        fs.exists(Config.MixFolder, function(exists) {
            if (exists === false) fs.mkdirSync(Config.MixFolder);
        });
    });
};
/*
 * upload file function
 */

let upload = function(files, reply) {
    fs.readFile(files.file[0].path, function(err, data) {
        checkFileExist();
        fs.writeFile(Config.MixInsideFolder + files.file[0].originalFilename, data, function(err) {
            if (err) return reply({
                code: '-1',
                msg: err
            });
            else return reply({
                code: '0',
                msg: 'ok',
                path: `http://${Config.proxyHost}:${Config.proxyPort}${Config.uploadFolder}/${files.file[0].originalFilename}`
            });
        });
    });
};

module.exports = [{
    method: 'POST',
    path: `/${GROUP_NAME}`,
    config: {
        payload: {
            maxBytes: 209715200,
            output: 'stream',
            parse: true
        },
        handler: function(requset, reply) {
            var form = new multiparty.Form();
            form.parse(requset.payload, function(err, fields, files) {
                if (err) return reply({
                    code: '-1',
                    msg: err
                });
                else upload(files, reply);
            });
        },
        tags: ['api', GROUP_NAME],
        auth: false,//false 配置为不通过jwt验证
        description: '上传文件接口',
        validate: {
            payload: {
                file: Joi.any()
                    .meta({ swaggerType: 'file' })
                    .description('文件')
            }
        }
    },
}]

/*
 * upload file
 */

// exports.uploadFile = {
//     payload: {
//         maxBytes: 209715200,
//         output: 'stream',
//         parse: false
//     },
//     handler: function(requset, reply) {
//         var form = new multiparty.Form();
//         form.parse(requset.payload, function(err, fields, files) {
//             if (err) return reply(err);
//             else upload(files, reply);
//         });
//     }
// };

// /*
//  * upload file function
//  */

// var upload = function(files, reply) {
//     fs.readFile(files.file[0].path, function(err, data) {
//         checkFileExist();
//         fs.writeFile(Config.MixInsideFolder + files.file[0].originalFilename, data, function(err) {
//             if (err) return reply(err);
//             else return reply('File uploaded to: ' + Config.MixInsideFolder + files.file[0].originalFilename);

//         });
//     });
// };